package utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import bean.Files;
import bean.Folders;

public class FolderUtils {
    private static final String STORAGE_FOLDER = "folder_data.json";
    private List<Folders> folderList = new ArrayList<>();
    private ObjectMapper objectMapper = new ObjectMapper();
	
    // 加载数据
    public List<Folders> loadFolder() {
        try {
            File file = new File(STORAGE_FOLDER);
            if (file.exists()) {
                folderList = objectMapper.readValue(file, new TypeReference<List<Folders>>() {});
            }
        } catch (IOException e) {
            System.err.println("加载数据失败: " + e.getMessage());
            folderList = new ArrayList<>();
        }
        return folderList;
    }
    
	//保存文件夹
    public void saveFolder() {
    	try {
            objectMapper.writerWithDefaultPrettyPrinter().writeValue(new File(STORAGE_FOLDER), folderList);
        } catch (IOException e) {
            System.err.println("保存数据失败: " + e.getMessage());
        }
    }
    private String createFolderId() {//用创建时刻的时间戳字符串，防止id重复
        java.util.Date now = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
        // 返回格式化后的字符串
        return sdf.format(now);
    }
    
    // 增删改查方法
    /**
            * 传入名称创建文件夹（即新分类）
     * @param folderName
     */
    public Folders addFolder(String folderName) {
    	Folders folder = new Folders();
    	folder.setFolderId(createFolderId());
    	folder.setFolderName(folderName);
        folderList.add(folder);
        saveFolder();
        return folder;
    }
    /**
     * 删除文件夹
     * @param folderId
     * @return
     */
    public boolean removeFolder(String folderId) {
        boolean removed = folderList.removeIf(folder -> folder.getFolderId().equals(folderId));
        if (removed) saveFolder();
        return removed;
    }
    /**
     * 更改文件夹名称
     * @param folderId
     * @param newFolderName
     * @return
     */
    public boolean updateFolder(String folderId, String newFolderName) {
        for (int i = 0; i < folderList.size(); i++) {
            if (folderList.get(i).getFolderId().equals(folderId)) {
                folderList.get(i).setFolderName(newFolderName);
                saveFolder();
                return true;
            }
        }
        return false;
    }
    /**
     * 获取文件夹列表
     * @return
     */
    public List<Folders> getAllFolders() {
        return new ArrayList<>(folderList); // 返回副本保护原始数据
    }
}
